package com.bbkb.quartz.resolver;


import com.bbkb.common.base.exception.BaseCheckException;
import com.bbkb.portal.constant.PortalConstants;
import com.bbkb.portal.dto.PortalUserInfo;
import com.bbkb.quartz.vo.Result;
import com.bbkb.tour.exception.TourExceptionEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;


/**
 * 异常解析器
 */
@ControllerAdvice
public class ExceptionResolver {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 拦截 BaseCheckException 异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = BaseCheckException.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest request, BaseCheckException e) {
        logger.error("Portal用户[{}]请求[{}]的时候出现警告:[{}]", this.getCurrentUserId(request), this.getErrorLogMsg(request), e.getDetail(), e);
        return new Result(e.getErrorCode(), e.getDetail());
    }

    /**
     * 异常分类处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.error("Portal用户[{}]请求[{}]的时候出现错误", this.getCurrentUserId(request), this.getErrorLogMsg(request), ex);
        return new Result(TourExceptionEnum.SERVER_ERROR.getKey(), TourExceptionEnum.SERVER_ERROR.getValue());
    }

    private String getErrorLogMsg(HttpServletRequest request) {
        StringBuilder errorLogMsg = new StringBuilder();
        errorLogMsg.append("url: ").append(request.getRequestURL().toString());
        if (StringUtils.isNotBlank(request.getQueryString())) {
            errorLogMsg.append("?").append(request.getQueryString());
        }
        // 获取查询参数
        Map<String, String[]> params = request.getParameterMap();
        if (params != null && !params.isEmpty()) {
            StringBuilder builder = new StringBuilder();
            params.forEach((k, v) -> {
                builder.append(",").append(k).append("=").append(Arrays.toString(v));
            });
            errorLogMsg.append(", params:").append(builder.substring(1));
        }
        return errorLogMsg.toString();
    }

    private Integer getCurrentUserId(HttpServletRequest request) {
        PortalUserInfo userInfo = (PortalUserInfo) request.getSession().getAttribute(PortalConstants.USER_INFO);
        return userInfo != null ? userInfo.getId() : null;
    }

}
